package example.conc;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.TimeUnit;

/**
 * a class to illustrate how to use reentrantLock
 *
 *      Lock l = ...;
        l.lock();
        try {
           // access the resource protected by this lock
        } finally {
           l.unlock();
        }
 * zhu.tan@gmail.com
 * 05-Jan-2010
 */
public class ReentrantLockEX implements Runnable {
    private static final ReentrantLock lock = new ReentrantLock(false);
    public static String sharedVariable = "";

    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                if (lock.tryLock(1, TimeUnit.MILLISECONDS)) { // Lock obtained
                    System.out.println("Lock Obtained by thread  : " + Thread.currentThread().getName());
                    sharedVariable += Thread.currentThread().getName() + " : locked \t" + i + "\n";
                } else { // Lock not obtained
                    sharedVariable += Thread.currentThread().getName() + " : unlocked \t" + i + "\n";
                }
                Thread.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (lock.isLocked()) {
                    lock.unlock();
                }
            }
        }
    }
}
